package io.sundial.console.task.service;

import io.sundial.console.Pagination;
import io.sundial.console.task.core.Logging;
import io.sundial.console.task.dao.LoggingRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 执行记录Service实现
 *
 * @author Payne 646742615@qq.com
 * 2019/1/14 13:34
 */
@Service
public class LoggingServiceBean implements LoggingService {

    @Resource
    private LoggingRepository loggingRepository;

    @Override
    public Pagination<Logging> search(String taskGroup, String taskName, String dateStart, String dateEnd, Logging.Status status, int pageNo, int pageSize) throws ParseException {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Order.desc("dateCreated")));

        Date startDate = StringUtils.isEmpty(dateStart) ? new Date(0L) : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStart);
        Date endDate = StringUtils.isEmpty(dateEnd) ? new Date() : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateEnd);

        Page<Logging> page = status == null
                ? loggingRepository.search(taskGroup, taskName, startDate, endDate, pageable)
                : loggingRepository.search(taskGroup, taskName, startDate, endDate, status, pageable);

        return new Pagination<>(page.getTotalElements(), page.getContent());
    }
}
